package graduation.project.mutant.strategy;

import java.util.ArrayList;

import graduation.project.body.Expression;
import graduation.project.body.Mutants;
import graduation.project.body.OriginExpression;
import graduation.project.exception.NonExpressionException;

public class LIFMutantsGen implements MutantsGenerator {

	public Mutants generateMutants(String expression, int mutantsNum) {

		try{
			OriginExpression originEx = new OriginExpression(expression);
			return generateMutants(originEx, mutantsNum);
		}catch(NonExpressionException e){
			System.out.println("LIFMutantsGen: the expression is invalid.");
			e.printStackTrace();
		}
		return null;
	}

	public Mutants generateMutants(OriginExpression originEx, int num) {
		
		int count = 0;
		String idnf = originEx.getDNF();
		Mutants result = new Mutants(originEx.getExpression(), "LIF");
		ArrayList<Expression> mutantSet = new ArrayList<Expression>();
		
		int termsNum = idnf.split("\\+").length;
		StringBuffer mutant = new StringBuffer();
		mutant.append(idnf);
		int beginPos = -1;
		int endPos = -1;
		
		String term;
		StringBuffer model = new StringBuffer();
		for(int i = 0; i < termsNum; i++){
			model.append(originEx.getModel());
			
			beginPos = endPos + 1;
			endPos = mutant.indexOf("+", beginPos);
			if(endPos < 0)
				endPos = mutant.length();
			term = mutant.substring(beginPos, endPos);
			term = term.replaceAll("!", "");
			for(int j = 0; j < term.length(); j++)
				model.deleteCharAt(model.indexOf("" + term.charAt(j)));
			
			for(int j = 0; j < model.length(); j++){
				try {
					mutant.insert(endPos, model.charAt(j));
					mutantSet.add(new Expression(mutant.toString()));
					if(num != -1 && ++count >= num)
						break;
					mutant.insert(endPos, '!');
					mutantSet.add(new Expression(mutant.toString()));
					mutant.delete(endPos, endPos + 2);
					if(num != -1 && ++count >= num)
						break;
				} catch (NonExpressionException e) {
					System.out.println("the expression is invalid expression");
					e.printStackTrace();
				}				
			}
			if(num != -1 && ++count >= num)
				break;
			model.delete(0, model.length());
		}
		
		result.setMutants(mutantSet);
		return result;
	}

}
